<template>
  <layout title="color颜色" :custom-content-style="customLayoutContentStyle" :safe-area-inset-bottom="false">

    <view class="color" :style="containerStyle">
      <!-- 左容器 -->
      <view class="left__container">
        <scroll-view
          class="left__scroll-view"
          :scroll-top="leftScrollScrollTop"
          scroll-y
          scroll-with-animation
        >
          <view class="left__content">
            <view
              id="left__item-0"
              class="left__item tn-flex-center"
              :class="[leftItemClass(0)]"
              :style="leftItemStyle(0)"
              @tap.stop="handleLeftItemClick(0)"
            >
              <tn-icon icon="logo-tuniao" size="48"></tn-icon>
            </view>
            <view
              id="left__item-1"
              class="left__item tn-flex-center"
              :class="[leftItemClass(1)]"
              :style="leftItemStyle(1)"
              @tap.stop="handleLeftItemClick(1)"
            >
              主
            </view>
            <view
              id="left__item-2"
              class="left__item tn-flex-center"
              :class="[leftItemClass(2)]"
              :style="leftItemStyle(2)"
              @tap.stop="handleLeftItemClick(2)"
            >
              酷
            </view>
            <view
              v-for="(item, index) in TuniaoColor"
              :key="index"
              :id="`left__item-${index+3}`"
              class="left__item"
              :class="[leftItemClass(index + 3, item)]"
              :style="leftItemStyle(index + 3)"
              @tap.stop="handleLeftItemClick(index + 3)"
            ></view>
          </view>
        </scroll-view>
      </view>

      <!-- 右容器 -->
      <view class="right__container">
        <scroll-view
          class="right__scroll-view"
          scroll-y
          scroll-with-animation
          :scroll-into-view="rightScrollIntoView"
          @scroll="handleRightScroll"
        >
          <!-- 图鸟配色 -->
          <view id="right__item-0" class="right__item">
            <view class="right__item__title">图鸟配色</view>
            <view class="right__item__content tn-shadow-blur" style="background-color: #01BEFF;">
              <view class="name">主色蓝</view>
              <view class="value">#01BEFF</view>
            </view>
            <view class="right__item__content tn-shadow-blur" style="background-color: #FBBD12;">
              <view class="name">主色橙</view>
              <view class="value">#FBBD12</view>
            </view>
            <view class="right__item__content tn-shadow-blur" style="background-color: #00FFC6;">
              <view class="name">点缀青</view>
              <view class="value tn-color-grey">#00FFC6</view>
            </view>
            <view class="right__item__content tn-shadow-blur" style="background-color: #FFF00D;">
              <view class="name tn-color-grey--disabled">点缀黄</view>
              <view class="value tn-color-grey">#FFF00D</view>
            </view>
            <view class="right__item__content tn-shadow-blur" style="background-color: #FF71D2;">
              <view class="name">辅助粉</view>
              <view class="value">#FF71D2</view>
            </view>
            <view class="right__item__content tn-shadow-blur" style="background-color: #82B2FF;">
              <view class="name">辅助蓝色</view>
              <view class="value">#82B2FF</view>
            </view>
            <view class="right__item__content tn-shadow-blur" style="background-color: #080808;">
              <view class="name">文字主色</view>
              <view class="value">#080808</view>
            </view>
            <view class="right__item__content tn-shadow-blur" style="background-color: #F4F4F4;">
              <view class="name tn-color-grey">背景主色</view>
              <view class="value tn-color-grey--disabled">#F4F4F4</view>
            </view>
          </view>

          <!-- type主题色 -->
          <view id="right__item-1" class="right__item">
            <view class="right__item__title">主题色</view>
            <view class="right__item__content tn-shadow-blur tn-type-primary">
              <view class="name">Primary</view>
              <view class="value">#01BEFF</view>
            </view>
            <view class="right__item__content inherit tn-shadow-blur tn-type-primary--light">
              <view class="name">Primary-light</view>
              <view class="value">#CCF2FF</view>
            </view>
            <view class="right__item__content tn-shadow-blur tn-type-success">
              <view class="name">Success</view>
              <view class="value">#00D886</view>
            </view>
            <view class="right__item__content inherit tn-shadow-blur tn-type-success--light">
              <view class="name">Success-light</view>
              <view class="value">#CCF7E7</view>
            </view>
            <view class="right__item__content tn-shadow-blur tn-type-warning">
              <view class="name">Warning</view>
              <view class="value">#FBBD12</view>
            </view>
            <view class="right__item__content inherit tn-shadow-blur tn-type-warning--light">
              <view class="name">Warning-light</view>
              <view class="value">#FEF2D0</view>
            </view>
            <view class="right__item__content tn-shadow-blur tn-type-danger">
              <view class="name">Danger</view>
              <view class="value">#FF444F</view>
            </view>
            <view class="right__item__content inherit tn-shadow-blur tn-type-danger--light">
              <view class="name">Danger-light</view>
              <view class="value">#FFDADC</view>
            </view>
            <view class="right__item__content tn-shadow-blur tn-type-info">
              <view class="name">Info</view>
              <view class="value">#9C9C9C</view>
            </view>
            <view class="right__item__content inherit tn-shadow-blur tn-type-info--light">
              <view class="name">Info-light</view>
              <view class="value">#F0F1F0</view>
            </view>
          </view>

          <!-- 酷炫背景颜色 -->
          <view id="right__item-2" class="right__item">
            <view class="right__item__title">酷炫背景色</view>
            <view
              v-for="item in 16"
              :key="item"
              class="right__item__content tn-shadow-blur"
              :class="[`tn-cool-bg-${item}`]"
            >
              <view class="name">Cool-bg-{{ item }}</view>
            </view>
          </view>

          <!-- 图鸟默认配色 -->
          <template
            v-for="(item, index) in TuniaoColor"
            :key="index"
          >
            <view :id="`right__item-${index + 3}`" class="right__item">
              <view class="right__item__title">{{ item.name }} - <text class="tn-text-cap">{{ item.color }}</text></view>
              <view
                v-for="(colorValue, colorKey, colorIndex) in item.value"
                :key="colorIndex"
                class="right__item__content inherit tn-shadow-blur"
                :class="[colorIndex === 0 ? `tn-bg-${item.color}` : `tn-bg-${item.color}--${String(colorKey)}`]"
              >
                <view class="name">{{ colorKey }}</view>
                <view class="value">{{ colorValue }}</view>
              </view>

              <!-- 单色渐变 -->
              <view class="right__item__title--sub tn-text-clip" :class="[`tn-bg-${item.color}--gradient--single`]">渐变色</view>
              <view
                v-if="!['gray','brown', 'orangered'].includes(item.color || '')"
                class="right__item__content inherit tn-shadow-blur"
                :class="[`tn-bg-${item.color}--gradient`]"
              >
                <view class="name">gradient</view>
              </view>
              <view
                class="right__item__content inherit tn-shadow-blur"
                :class="[`tn-bg-${item.color}--gradient--light`]"
              >
                <view class="name">gradient-light</view>
              </view>
              <view
                class="right__item__content inherit tn-shadow-blur"
                :class="[`tn-bg-${item.color}--gradient--single`]"
              >
                <view class="name">gradient-single</view>
              </view>
            </view>
          </template>

          <view style="height: 20rpx;"></view>
        </scroll-view>
      </view>
    </view>

  </layout>
</template>

<script lang="ts" setup>
import {
  onMounted, 
  nextTick, 
  ref, 
  computed, 
  CSSProperties,
  getCurrentInstance,
  ComponentInternalInstance
} from 'vue'
import useSystemInfo from '@/tuniao-ui/libs/hooks/useSystemInfo'
import Layout from '@/components/layout/index.vue'
import { TuniaoColor, TuniaoColorValue } from './lib/color'
import TnIcon from '@/tuniao-ui/components/tn-icon/src/Icon.vue'
import { getRectInfo } from '@/tuniao-ui/utils'

// 系统信息
const { updateSystemInfo, systemInfo, customNavbar } = useSystemInfo()

const customLayoutContentStyle: CSSProperties = {
  padding: '0px'
}
// 容器样式
const containerStyle = computed<CSSProperties>(() => {
  let style: CSSProperties = {}
  if (windowHeight.value) style.height = windowHeight.value + 'px'
  return style
})
// 左容器对应的样式
const leftItemStyle = computed<(index: number) => CSSProperties>(() => {
  return (index) => {
    let style: CSSProperties = {}
    style.animationDelay = `${index * 0.1}s`
    if (index === 0 || index === 1 || index === 2) style.backgroundColor = '#01BEFF'
    return style
  }
})

// 左容器Item对应的类
const leftItemClass = computed<(index: number, item?: TuniaoColorValue) => string>(() => {
  return (index, item) => {
    let clazz: string[] = []
    if (index === currentLeftIndex.value) clazz.push('tn-shadow-blur active')
    if (item?.color) clazz.push(`tn-bg-${item.color}`)
    return clazz.join(' ')
  }
})

const instance = getCurrentInstance() as ComponentInternalInstance
let windowHeight = ref<number>(0)
// 初始化容器的高度, 因为scroll-view需要指定高度才可以进行滚动使用
let initCount: number = 0
const initContainer = () => {
  if (!Object.keys(systemInfo).length) {
    if (initCount > 10) {
      return console.error('[demo-color]初始化容器失败')
    }
    setTimeout(() => {
      initContainer()
      initCount++
    }, 50);
    return
  }

  initCount = 0
  windowHeight.value = systemInfo.value.safeAreaHeight - customNavbar.value.height + customNavbar.value.statusHeight
  getLeftContainerRectInfo()
  getRightContainerRectInfo()
}

// 获取滚动容器相关信息
type LeftItemRect = {
  top: number,
  height: number
}
let getRectCount: number = 0
let leftItemRects: LeftItemRect[] = []
let leftScrollViewTop: number = 0
let leftScrollScrollTop = ref<number>(0)
const getLeftContainerRectInfo = async () => {
  const leftScrollRect = await getRectInfo('.left__scroll-view', instance)
  if (!leftScrollRect) {
    if (getRectCount > 10) {
      return console.error('[demo-color]获取左scrollview布局信息失败')
    }
    setTimeout(() => {
      getLeftContainerRectInfo()
      getRectCount++
    }, 50);
    return
  }
  getRectCount = 0
  const query = uni.createSelectorQuery().in(instance)
  for(let i = 0; i < TuniaoColor.length + 3; i++) {
    query.select(`#left__item-${i}`).boundingClientRect(() => {})
  }
  query.exec((res: UniApp.NodeInfo[]) => {
    if (!res) {
      if (getRectCount > 10) {
        return console.error('[demo-color]获取左scrollview布局信息失败')
      }
      setTimeout(() => {
        getRightContainerRectInfo()
        getRectCount++
      }, 50);
      return
    }
    getRectCount = 0

    res.map(item => {
      leftItemRects.push({
        top: item.top || 0,
        height: item.height || 0
      })
    })
  })
  
  leftScrollViewTop = leftScrollRect.top || 0
}

type RightItemRects = {
  top: number,
  bottom: number
}
let rightItemRects: RightItemRects[] = []
const getRightContainerRectInfo = async () => {
  const query = uni.createSelectorQuery().in(instance)
  for(let i = 0; i < TuniaoColor.length + 3; i++) {
    query.select(`#right__item-${i}`).boundingClientRect(() => {})
  }
  query.exec((res: UniApp.NodeInfo[]) => {
    if (!res) {
      if (getRectCount > 10) {
        return console.error('[demo-color]获取右scrollview布局信息失败')
      }
      setTimeout(() => {
        getRightContainerRectInfo()
        getRectCount++
      }, 50);
      return
    }
    getRectCount = 0

    res.map(item => {
      rightItemRects.push({
        bottom: item.bottom || 0,
        top: item.top || 0
      })
    })
    // console.log(rightItemRects);
  })
}

// 当前选中查看颜色信息的index
let currentLeftIndex = ref<number>(0)
let isScroll = ref<boolean>(false)
// rightScrollView滚动到指定的位置
let rightScrollIntoView = computed<string>(() => {
  if (isScroll.value) return ''
  return 'right__item-' + currentLeftIndex.value
})

// 处理leftItem点击事件
const handleLeftItemClick = (index: number, type: 'scroll' | 'click' = 'click') => {
  isScroll.value = type === 'scroll'
  currentLeftIndex.value = index
  scrollToCenter()
}

// 处理右scrollView滚动事件
const handleRightScroll = (e: any) => {
  // console.log(e.detail.scrollTop, e.detail.scrollTop + windowHeight.value);
  const index = rightItemRects.findIndex((item: RightItemRects) => {
    return item.top - e.detail.scrollTop > 0 && item.top - e.detail.scrollTop < windowHeight.value
  })
  // console.log(index);
  handleLeftItemClick(index < 0 ? currentLeftIndex.value : index, 'scroll')
}

// 滚动scrollView保持活动的标签在屏幕中间
const scrollToCenter = () => {
  // 获取当前选中的item节点信息
  const itemRectInfo: LeftItemRect = leftItemRects[currentLeftIndex.value]
  if (!itemRectInfo) return

  // 选中item的上边到scroll-view顶部的距离
  const offsetTop = itemRectInfo.top - leftScrollViewTop
  // 设置scrollView滚动距离
  const scrollTopValue = offsetTop - ((windowHeight.value - itemRectInfo.height) / 2)
  leftScrollScrollTop.value = scrollTopValue < 0 ? 0 : scrollTopValue
}

updateSystemInfo()
onMounted(() => {
  nextTick(() => {
    setTimeout(() => {
      initContainer()
    }, 50);
  })
})
</script>

<style lang="scss" scoped>
@import './main.scss';
</style>
